<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cart</title>
    <link rel="stylesheet" href="/static/home/css/cart.css">
</head>

<body>
{include file="/index/head"/}
<div class="carts-container">
    <div class="carts-title">
        <h1>Cart</h1>
    </div>
    <div class="carts-table">
        <table>
            <thead>
            <tr>
                <th>Product</th>
                <th>Quantity</th>
                <th>Total</th>
            </tr>
            </thead>
            <tbody id="t">
            <!--这里是动态生成的容器-->
            </tbody>
        </table>
    </div>

    <footer class="u-flex-col u-col-bottom u-text-right">
        <p id="total-price">Total: $0.00 USB</p>
        <p style="color: rgba(28, 28, 28, 0.65);">Excluding taxes and shipping fees</p>
        <p>Share with Member</p>
        <div>
            <hr style="width: 400px;">
        </div>
        <strong>Your Email</strong>
        <div>
            <input style="color: #000;" type="text" id="user-email" placeholder="Please enter your email address">
        </div>
        <div style="max-width: 400px;">
            <strong>Tips:</strong>
            <span>We will contact you based on the email you provided.</span>
        </div>
        <div class="button-group" style="width: 200px;">
            <button class="button-grup-item" id="checkoutButton">CHECKOUT</button>
        </div>
    </footer>
</div>


<!-- 加载 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
    <div>Submitting...</div>
</div>
</body>



{include file="/index/foot"/}




<script>
    // 显示加载
    function showLoading() {
        document.getElementById('loadingOverlay').style.display = 'flex';
    }

    // 隐藏加载
    function hideLoading() {
        document.getElementById('loadingOverlay').style.display = 'none';
    }
</script>








<script>
    // 提交
    $('#checkoutButton').click(function() {
        const productData = JSON.parse(localStorage.getItem('cart_list') || '[]');
        const userEmail = document.getElementById('user-email').value;

        console.log(productData, userEmail);

        if(productData.length < 1) {
            alert('请选择商品');
            return;
        }

        if(!userEmail) {
            alert('请输入邮箱');
            return;
        }

        showLoading();
        $.ajax({
            url: '/api/order/create',
            type: 'POST',
            data:  { data: productData, email: userEmail,token:"{$token|default=''}" },
            success: function(response) {
                showLoading();
            },
            error: function(error) {
                // 懒得处理了
            },
            complete: function() {
                hideLoading();
            }
        });

    });
</script>









<script>
    // 更新购物车数据到本地存储并刷新显示
    function updateCart(cartData) {
        localStorage.setItem('cart_list', JSON.stringify(cartData));
        renderCart();
        updateTotal();
    }

    // 计算并显示总金额
    function updateTotal() {
        const total_price = document.getElementById('total-price');
        let data = JSON.parse(localStorage.getItem('cart_list') || '[]');
        let total = data.reduce((sum, item) => sum + (item.price * item.number), 0);
        total_price.textContent = `Total:$${total.toFixed(2)} USB`;
    }

    // 渲染购物车内容
    function renderCart() {
        let data = JSON.parse(localStorage.getItem('cart_list') || '[]');
        let string = '';

        if (data.length === 0) {
            string = '<tr><td colspan="3" style="text-align: center;">Your shopping cart is empty</td></tr>';
        }
        else {
            data.forEach((item, index) => {
                string += `<tr data-id="${item.id}" data-attr="${item.attr}">
                    <td>
                        <div class="u-flex" style="gap: 20px;">
                            <img style="width: 120px;height: 120px;" src="${item.image}">
                            <div class="u-flex-col" style="flex-direction: column;">
                                <a href="javascript:;">${item.title}</a>
                                <div><span class="smallcaps">${item.attr}</span></div>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="u-flex-col u-col-center">
                            <div class="quantity">
                                <div class="cart_input-sub">-</div>
                                <input class="cart_input" type="text" style="text-align: center" value="${item.number}">
                                <div class="cart_input-add">+</div>
                            </div>
                            <div class="remove">
                                Remove
                            </div>
                        </div>
                    </td>
                    <td>
                        <div>$${(item.price * item.number).toFixed(2)}</div>
                    </td>
                </tr>`;
            });
        }

        document.getElementById('t').innerHTML = string;
        attachEventListeners();
    }

    // 为动态元素添加事件监听器
    function attachEventListeners() {
        const cart_input_sub = document.querySelectorAll(".cart_input-sub");
        const cart_input_add = document.querySelectorAll(".cart_input-add");
        const cart_input = document.querySelectorAll(".cart_input");
        const remove_buttons = document.querySelectorAll(".remove");

        // 减少商品数量
        cart_input_sub.forEach((sub, i) => {
            sub.addEventListener("click", function() {
                let cartData = JSON.parse(localStorage.getItem('cart_list') || '[]');
                if (cart_input[i].value > 1) {
                    cart_input[i].value--;
                    cartData[i].number = parseInt(cart_input[i].value);
                    updateCart(cartData);
                }
            });
        });

        // 增加商品数量
        cart_input_add.forEach((add, i) => {
            add.addEventListener("click", function() {
                let cartData = JSON.parse(localStorage.getItem('cart_list') || '[]');
                if (cart_input[i].value < 99) {
                    cart_input[i].value++;
                    cartData[i].number = parseInt(cart_input[i].value);
                    updateCart(cartData);
                }
            });
        });

        // 手动输入数量变化
        cart_input.forEach((input, i) => {
            input.addEventListener("change", function() {
                let cartData = JSON.parse(localStorage.getItem('cart_list') || '[]');
                let newValue = parseInt(input.value) || 1;
                if (newValue < 1) newValue = 1;
                if (newValue > 99) newValue = 99;
                input.value = newValue;
                cartData[i].number = newValue;
                updateCart(cartData);
            });
        });

        // 移除商品
        remove_buttons.forEach((button, i) => {
            button.addEventListener("click", function() {
                let cartData = JSON.parse(localStorage.getItem('cart_list') || '[]');
                cartData.splice(i, 1);
                updateCart(cartData);
            });
        });


        // 更新购物车tag数量
        setCartIconTagNum();
    }

    // 页面加载时初始化购物车
    window.onload = function() {
        renderCart();
        updateTotal();
    }
</script>
</html>